package com.igoal.utils;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;

import com.igoal.entity.Audit;
import com.igoal.entity.DataStatus;

public class EntityUtils {
	private static final Log logger=  LogFactory.getLog(EntityUtils.class);
	
	public static void createNewAuditInformation(Audit audit){
		audit.setCreateDate(new Date());
		audit.setUpdateDate(new Date());
		audit.setStatus(DataStatus.USING);
	}
	
	public static void updateAuditInformation(Audit audit){
		audit.setUpdateDate(new Date());
	}
	
	/**
	 * +1 to property value. <br/> only support non dynamic dot value (Byte, Short, Integer, Long)
	 * @param obj object contains propertyName
	 * @param propertyName property name
	 */
	public static void increasePropertyValue(Object obj, String propertyName){
		BeanWrapper bw = new BeanWrapperImpl(obj);
		try{			
			Object value = bw.getPropertyValue(propertyName);
			if(value instanceof Integer){
				Integer i = (Integer) value;
				i++;
				bw.setPropertyValue(propertyName, i);
			}else if(value instanceof Long){
				Long l = (Long) value;
				l++;
				bw.setPropertyValue(propertyName, l);				
			}else if(value instanceof Short){
				Short s = (Short) value;
				s++;
				bw.setPropertyValue(propertyName, s);
			}else if(value instanceof Byte){
				Byte b = (Byte) value;
				b++;
				bw.setPropertyValue(propertyName, b);
			}
		}catch (BeansException e) {
			logger.error(e);
		}
	}
	
	/**
	 * -1 to property value. <br/> only support non dynamic dot value (Byte, Short, Integer, Long)
	 * @param obj object contains propertyName
	 * @param propertyName property name
	 */
	public static void descreasePropertyValue(Object obj, String propertyName){
		BeanWrapper bw = new BeanWrapperImpl(obj);
		try{			
			Object value = bw.getPropertyValue(propertyName);
			if(value instanceof Integer){
				Integer i = (Integer) value;
				if(i <= 0){
					i=0;
				}else{
					i--;
				}
				bw.setPropertyValue(propertyName, i);
			}else if(value instanceof Long){
				Long l = (Long) value;
				if(l <= 0L){
					l = 0L;
				}else{
					l--;
				}
				bw.setPropertyValue(propertyName, l);				
			}else if(value instanceof Short){
				Short s = (Short) value;
				if(s <= 0){
					s = 0;
				}else{
					s--;
				}
				bw.setPropertyValue(propertyName, s);
			}else if(value instanceof Byte){
				Byte b = (Byte) value;
				if(b <= 0){
					b = 0;
				}else{
					b--;
				}
				bw.setPropertyValue(propertyName, b);
			}
		}catch (BeansException e) {
			logger.error(e);
		}
	}
}
